package com.gupao.zigong.singleton.container;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zigong
 * @description 线程安全的容器式单例
 * @date 2020/9/17 21:08
 */
public class ContainerSingletonThreadSafe {
    /**
     * 初始化一个静态容器
     */
    private static Map<String, Object> container = new ConcurrentHashMap<>();

    /**
     * 私有化构造器
     */
    private ContainerSingletonThreadSafe() {

    }

    /**
     * 从容器中获取bean
     *
     * @param className 类的完全限定名
     * @return
     */
    public static Object getBean(String className) {
        Object bean = null;
        synchronized (container) {
            if (!container.containsKey(className)) {
                try {
                    bean = Class.forName(className).newInstance();
                    // 存入容器
                    container.put(className, bean);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else {
                return container.get(className);
            }
        }
        return bean;
    }
}
